package com.asa.base

import android.content.res.Resources
import android.os.Bundle
import androidx.annotation.ColorRes
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.gyf.immersionbar.ktx.immersionBar
import me.jessyan.autosize.AutoSizeCompat


abstract class BaseActivity<B: ViewDataBinding,VM:BaseViewModel>:AppCompatActivity() {


    protected lateinit var binding:B
        private set

    protected lateinit var viewModel:VM
        private set



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewConfig()
        initContentView()
        initData()
        systemUiAdapter()
    }


    override fun getResources(): Resources {
        val resources = super.getResources()
        AutoSizeCompat.autoConvertDensityOfGlobal(resources)
        return resources
    }


    private fun initContentView() {
        binding = DataBindingUtil.inflate(layoutInflater,getLayoutId(),null,false)
        setContentView(binding.root)
        binding.lifecycleOwner = this
        val vm = createViewModel()
        viewModel = ViewModelProvider(this,BaseViewModel.createViewModelFactory(vm)).get(vm::class.java)
        viewModel.application = application
        lifecycle.addObserver(viewModel)

    }


    @LayoutRes
    protected abstract fun getLayoutId():Int

    /**
     *  配置Activity flag  比如配置状态栏显示也隐藏配置
     */
    open fun initViewConfig(){

    }

    /**
     *  系统沉浸式 封装
     */
    private fun systemUiAdapter(){
        if (isImmersion()){
            immersionBar {
                fitsSystemWindows(isFitsSystemWindows())
                statusBarColor(initStatusColor())
                transparentNavigationBar()
                fullScreen(true)
            }
        }
    }

    /**
     *  true 系统预留状态栏出来  比如设置title类型 要设置true 然后设置状态栏颜色 如果是图片沉浸式要设置false
     */
    open fun isFitsSystemWindows() = true



    /**
     *  true  需要显示沉浸效果
     */
    open fun isImmersion() = true

    /**
     *  子类可以根据自己设置状态栏颜色
     */
    @ColorRes
    open fun initStatusColor() :Int= R.color.color_primary

    /**
     *  子类可以根据自己设置导航栏颜色
     */
    @ColorRes
    open fun initNavigationBarColor() :Int= R.color.color_primary


    abstract fun initData()

    abstract fun createViewModel():VM


    override fun onDestroy() {
        super.onDestroy()
        binding.unbind()
    }


}